import { defineStore } from 'pinia'
import { getUserInfo } from '@/api/user'
import { login, logout } from '@/api/auth'

export const useUserStore = defineStore('user', {
    state: () => ({
        userInfo: null,
        userId: null,
    }),

    actions: {
        setUserId(id) {
            this.userId = id
        },

        async getUserInfo() {
            if (!this.userId) {
                throw new Error('用户ID不存在')
            }
            try {
                const response = await getUserInfo(this.userId)
                this.userInfo = response.data.userName
                localStorage.setItem('userName', response.data.userName)
                console.log('获取用户信息成功', this.userInfo)
                return response.data
            } catch (error) {
                console.error('获取用户信息失败:', error)
                throw error
            }
        },

        clearUserInfo() {
            this.userInfo = null
            this.userId = null
            localStorage.removeItem('username')
        },

        async login(userInfo) {
            try {
                const res = await login(userInfo)

                // 从 res.data 中获取数据
                const { token, id } = res.data || {}
                if (!token || !id) {
                    throw new Error('登录失败：未获取到必要信息')
                }

                // 保存token和userId
                localStorage.setItem('token', token)
                this.setUserId(id)

                return res
            } catch (error) {
                console.error('Login error:', error)
                throw error
            }
        },

        async logout() {
            try {
                await logout()
                this.token = ''
                this.userInfo = null
                localStorage.removeItem('token')
                router.push("/login");
            } catch (error) {
                throw error
            }
        }
    }
}) 